import { Component, OnInit, Input } from '@angular/core';
import{ ActivatedRoute, Params } from  '@angular/router';
import { MenuItem } from 'primeng/api';
import { MessageService } from 'primeng/api';
import { Comment, CommentService } from '../../service/comment.service';
import { SystemNotice, SystemNoticeService } from '../../service/system-notice.service';
import { MyCookie } from '../../utils/my-cookie';
import * as $ from 'jquery';
import { MarkdownFile } from '../../model/MarkdownFile';
import { CookieService } from 'ngx-cookie-service';
import { pairs } from 'rxjs';

let PUB_INTERVAL = 10000;  // ms

@Component({
  selector: 'app-comment',
  templateUrl: './comment.component.html',
  styleUrls: ['./comment.component.css']
})
export class CommentComponent implements OnInit {
  @Input() ReadingMdFile:MarkdownFile;

  userLiked:boolean;
  dealingComment:Comment;  // 记录当前操作的评论
  comments:Comment[];   // 当前阅读的博客对应的评论
  altDown = {"comment":false, "response":false, "update":false};  // 记录alt键按下情况，实现alt+Enter发布
  ableToPub = {"comment":true, "response":true, "update":true} // 防止频繁提交

  constructor(public commentService:CommentService, public cookieService:CookieService, 
              private route:ActivatedRoute, private msgService:MessageService, private systemNoticeService:SystemNoticeService) { }

  ngOnInit():void { }

  ngOnChanges():void {  // 当@Input改变时
    let inter = setInterval(()=>{
      if(this.ReadingMdFile==undefined){return;}
      clearInterval(inter);
      this.commentService.GetComment("blog", "fatherId", this.ReadingMdFile.id).subscribe(res=>{
        this.comments = [];
        for(let key in res){ 
          let tmp = <Comment>res[key];
          let date = new Date(parseInt(tmp.time+"000"));
          tmp.timeStr = date.getFullYear()+"-"+(date.getMonth()+1)+"-"+date.getDate()+" "+date.toTimeString().substring(0,8);
          tmp.response = [];
          this.comments.push(tmp); 
        }
      });
    }, 100);
  }

  AddResponseClicked(event:any, comment:Comment){
    if(comment["resShown"] != true){
      comment["resShown"] = true;
      this.dealingComment = comment;
      let resInput = document.createElement('textarea');
      comment["resInputElement"] = resInput;
      resInput.id = "res-input";
      resInput.placeholder = "回复"+"@"+comment.owner+"  Alt+Enter发布";
      resInput.onfocus = this.OnInputFocus.bind(this);
      resInput.onkeydown = this.AddResponseKeyDown.bind(this);
      resInput.onkeyup = this.AddResponseKeyUp.bind(this);
      resInput.style["border-radius"] = '20px';
      resInput.style["padding"] = '10px';
      resInput.style["font-size"] = '14px';
      resInput.style["width"] = '60%';
      resInput.style["margin-top"] = '20px';
      let resSubmit = document.createElement('div');
      comment["resSubmitElement"] = resSubmit;
      resSubmit.onclick = this.AddResponse.bind(this);
      resSubmit.innerText = "回复";
      resSubmit.style["line-height"] = '36px';
      resSubmit.style["width"] = '8%';
      resSubmit.style["margin-left"] = '65%';
      resSubmit.style["border-radius"] = '16px';
      resSubmit.style["font-size"] = '14px';
      resSubmit.style["font-weight"] = 'bold';
      resSubmit.style["color"] = 'white';
      resSubmit.style["text-align"] = 'center';
      resSubmit.style["background-color"] = 'rgb(4, 0, 255)';
      event.target.parentNode.appendChild(resInput);
      event.target.parentNode.appendChild(resSubmit);
    }else{
      comment["resShown"] = false;
      comment["resInputElement"].remove();
      comment["resSubmitElement"].remove();
    }
  }
  AddResponseKeyDown(event: KeyboardEvent){ 
    if(event.key=="Alt"){ 
      this.altDown["response"] = true;
    }
  }
  AddResponseKeyUp(event: KeyboardEvent){ 
    if(event.key=="Alt"){
      this.altDown["response"] = false;
    }else if(event.key=="Enter" && this.altDown["response"]){ 
      this.altDown["response"] = false;
      this.AddResponse(); 
    } 
  }
  AddResponse(){
    let content = <string> $("#res-input").val();
    let fatherContent;
    let commentId;
    if(!this.PublishCheck("response", content))return;
    // 拼接回复content，由父评论的content后一部分和新评论内容组成
    if(this.dealingComment.commentId == -1){    // 一级评论
      fatherContent = this.dealingComment.content;
      commentId = this.dealingComment.id;
    }else{                                      // 回复
      fatherContent = this.dealingComment.content.split("-<br>")[1];
      commentId = this.dealingComment.commentId;
    }
    // 论坛风格
    let fullContent = "回复@"+this.dealingComment.owner+" "+this.dealingComment.timeStr+"\n"+
      fatherContent+"\n"+
      "</div>----------"+"\n"+
      content;
    fullContent = this.text2HTML(fullContent);
    fullContent = "<div style='background-color:rgb(158, 183, 236);width:95%;padding:12px'>" + fullContent;
    // 简易风格
    // let fullContent = "回复@"+this.dealingComment.owner+" "+this.dealingComment.timeStr+"\n"+"</b>----------"+"\n"+content;
    // fullContent = this.text2HTML(fullContent);
    // fullContent = "<b style='color:rgb(10, 29, 65)'>" + fullContent;
    let userId = this.cookieService.get("userId")!=""?parseInt(this.cookieService.get("userId")):-1;
    this.commentService.AddComment("blog", this.ReadingMdFile.id, commentId, userId, fullContent).subscribe(res=>{
      if(res.indexOf("Success")!=-1){
        this.msgService.add({severity:'success', summary:'成功', detail:"添加回复成功"});
        let dataBaseId = parseInt(res.substring(7));
        this.AddCommentAtFront(dataBaseId, "blog", this.ReadingMdFile.id, commentId, userId, fullContent);
        this.dealingComment["resShown"] = false;
        this.dealingComment["resInputElement"].remove();
        this.dealingComment["resSubmitElement"].remove();
        // 防止连续重复操作
        this.ableToPub["response"]=false;
        setTimeout(()=>{
          this.ableToPub["response"]=true;
        }, PUB_INTERVAL);
        // 添加一条系统通知
        // let noticeContent = "您的评论:<br><b>"+this.dealingComment.content+"</b><br>收到了一条回复";
        // let firstId = this.dealingComment.commentId==-1?this.dealingComment.id:this.dealingComment.commentId;
        // let secondId = this.dealingComment.commentId==-1?0:this.dealingComment.id;
        // this.systemNoticeService.Add("response", "blog", this.ReadingMdFile.id, firstId, secondId, 
        //   this.dealingComment.userId, parseInt(this.cookieService.get("userId")), noticeContent).subscribe(res=>{});
      }
    })
  }

  UpdateCommentClicked(event:any, comment:Comment){
    let content:string;
    if(comment.commentId==-1){ content = comment.content; }
    else{ content = comment.content.split("-<br>")[1]; }

    if(comment["updateShown"] != true){
      comment["updateShown"] = true;
      this.dealingComment = comment;
      let updateInput = document.createElement('textarea');
      comment["updateInputElement"] = updateInput;
      updateInput.id = "update-input";
      updateInput.textContent = this.HTML2text(content);
      updateInput.onfocus = this.OnInputFocus.bind(this);
      updateInput.onkeydown = this.UpdateCommentKeyDown.bind(this);
      updateInput.onkeyup = this.UpdateCommentKeyUp.bind(this);
      updateInput.style["border-radius"] = '20px';
      updateInput.style["padding"] = '10px';
      updateInput.style["font-size"] = '14px';
      updateInput.style["width"] = '60%';
      updateInput.style["margin-top"] = '20px';
      let updateSubmit = document.createElement('div');
      comment["updateSubmitElement"] = updateSubmit;
      updateSubmit.onclick = this.UpdateComment.bind(this);
      updateSubmit.innerText = "更新";
      updateSubmit.style["line-height"] = '36px';
      updateSubmit.style["width"] = '8%';
      updateSubmit.style["margin-left"] = '65%';
      updateSubmit.style["border-radius"] = '16px';
      updateSubmit.style["font-size"] = '14px';
      updateSubmit.style["font-weight"] = 'bold';
      updateSubmit.style["color"] = 'white';
      updateSubmit.style["text-align"] = 'center';
      updateSubmit.style["background-color"] = 'rgb(4, 0, 255)';
      event.target.parentNode.appendChild(updateInput);
      event.target.parentNode.appendChild(updateSubmit);
    }else{
      comment["updateShown"] = false;
      comment["updateInputElement"].remove();
      comment["updateSubmitElement"].remove();
    }
  }
  UpdateCommentKeyDown(event: KeyboardEvent){ 
    if(event.key=="Alt"){ 
      this.altDown["update"] = true;
    }
  }
  UpdateCommentKeyUp(event: KeyboardEvent){ 
    if(event.key=="Alt"){
      this.altDown["update"] = false;
    }else if(event.key=="Enter" && this.altDown["update"]){ 
      this.altDown["update"] = false;
      this.UpdateComment(); 
    } 
  }
  UpdateComment(){
    let content = <string> $("#update-input").val();
    if(!this.PublishCheck("update", content))return;
    content = this.text2HTML(content);
    if(this.dealingComment.commentId==-1){ 
      content = content;
    } else { 
      content = this.dealingComment.content.split("-<br>")[0] + "-<br>" + content; 
    }
    this.commentService.UpdateComment(this.dealingComment.id, content).subscribe(res=>{
      if(res == "Success"){
        this.msgService.add({severity:'success', summary:'成功', detail:"评论更新成功"});
        // 在前端更新
        this.dealingComment.content = content;
        this.dealingComment["updateShown"] = false;
        this.dealingComment["updateInputElement"].remove();
        this.dealingComment["updateSubmitElement"].remove();
        // 防止连续重复操作
        this.ableToPub["update"]=false;
        setTimeout(()=>{
          this.ableToPub["update"]=true;
        }, PUB_INTERVAL);
      }
    })
  }
  
  DeleteCommentClicked(comment:Comment){
    this.commentService.DeleteComment(comment.id).subscribe(res=>{
      if(res == "Success"){
        this.msgService.add({severity:'success', summary:'成功', detail:"删除评论成功"});
        // 在前端删除
        if(comment.commentId == -1){  // 一级评论
          for(let index in this.comments){
            if(this.comments[index].id == comment.id){
              this.comments.splice(parseInt(index), 1);
              break;
            }
          }
        }else{
          for(let index in this.comments){
            let responses = this.comments[index].response;
            for(let index_ in responses){
              if(responses[index_].id == comment.id){
                responses.splice(parseInt(index_), 1);
                this.comments[index].resCounts -= 1;
              }
            }
          }
        }
      }
    })
  }

  LikeBlog(){
    // if(this.cookieService.get("username") == undefined){
    //   this.msgService.add({severity:'error', summary:'未登录', detail:"请登录后才可点赞哦"});
    // }
    // this.blogService.LikeBlog(this.blogService.readingBlog.title, this.userService.currentUser.username).subscribe(res=>{
    //   if(res == "Success"){
    //     if(this.userLiked){  // 若已点赞过则在前端也取消
    //       this.userLiked = false;
    //       let blogID = this.blogService.readingBlog.id.toString();
    //       let regStr = ";"+blogID+";";
    //       this.userService.currentUser.likedBlog = this.userService.currentUser.likedBlog.replace(RegExp(regStr), ";");
    //       this.blogService.readingBlog.likedTimes -= 1;
    //     }else{
    //       this.userLiked = true;
    //       this.userService.currentUser.likedBlog += this.blogService.readingBlog.id + ";";
    //       this.blogService.readingBlog.likedTimes += 1;
    //       // 添加一条系统通知,1为管理员用户id
    //       let noticeContent = "博客<b>"+this.blogService.readingBlog.title+"</b>收获了一次点赞!";
    //       this.systemNoticeService.Add("like", "blog", this.blogService.readingBlog.id, 0, 0, 
    //         1, this.userService.currentUser.id, noticeContent).subscribe(res=>{});
    //     } 
    //   }
    // })
  }

  AddCommentKeyDown(event: KeyboardEvent){ 
    if(event.key=="Alt"){ 
      this.altDown["comment"] = true;
    }
  }
  AddCommentKeyUp(event: KeyboardEvent){ 
    if(event.key=="Alt"){
      this.altDown["comment"] = false;
    }else if(event.key=="Enter" && this.altDown["comment"]){ 
      this.altDown["comment"] = false;
      this.AddComment(); 
    } 
  }
  AddComment(){
    let content = <string> $("#comment-input").val();
    if(!this.PublishCheck("comment", content))return;
    content = this.text2HTML(content);
    let userId = this.cookieService.get("userId")!=""?parseInt(this.cookieService.get("userId")):-1;
    this.commentService.AddComment("blog", this.ReadingMdFile.id, -1, userId, content).subscribe(res=>{
      if(res.indexOf("Success")!=-1){
        this.msgService.add({severity:'success', summary:'成功', detail:"添加评论成功"});
        let dataBaseId = parseInt(res.substring(7));
        this.AddCommentAtFront(dataBaseId, "blog", this.ReadingMdFile.id, -1, userId, content);
        // 防止连续重复操作
        this.ableToPub["comment"]=false;
        setTimeout(()=>{
          this.ableToPub["comment"]=true;
        }, PUB_INTERVAL);
        // 添加一条系统通知,1为管理员用户id
        // let noticeContent = "博客<b>"+this.ReadingMdFile.filename+"</b>收到一条评论:<br><b>"+content+"</b>";
        // this.systemNoticeService.Add("comment", "blog", this.ReadingMdFile.id, 0, 0, 
        //   1, parseInt(this.cookieService.get("userId")), noticeContent).subscribe(res=>{});
      }
    })
  }

  ShowResponse(comment:Comment){
    if(comment.response.length == 0){   // 展开
      this.commentService.GetComment("blog", "commentId", comment.id).subscribe(res=>{
        for(let key in res){ 
          let tmp = <Comment>res[key];
          let date = new Date(parseInt(tmp.time+"000"));
          tmp.timeStr = date.getFullYear()+"-"+(date.getMonth()+1)+"-"+date.getDate()+" "+date.toTimeString().substring(0,8);
          comment.response.push(tmp); 
        }
      })
    }else{    // 收回
      comment.response = [];
    }
  }

  // 判断当前用户是否点赞过本文
  // CheckUserLiked(){
  //   let blogID = this.ReadingMdFile.id.toString();
  //   let regStr = ";"+blogID+";";
  //   if(this.userService.currentUser.likedIds.search(RegExp(regStr)) != -1){  // 若点赞过
  //     this.userLiked = true;
  //   }else { this.userLiked = false }
  // }

  OnInputFocus(){
    if(this.cookieService.get("userId")==""){
      this.msgService.add({severity:'warn', summary:'未登陆', detail:'只能以匿名用户身份评论'});
    }
  }

  private text2HTML(text:string){ return text.replace(/\n/g,"<br>").replace(/ /g,"&nbsp;&nbsp;"); }
  private HTML2text(HTML:string){ return HTML.replace(/<br>/g,"\n").replace(/&nbsp;&nbsp;/g," "); }

  private PublishCheck(type:string, input:string):boolean{
    if(!this.ableToPub[type]){
      this.msgService.add({severity:'error', summary:'发布过于频繁', detail:'两次发布间应间隔'+PUB_INTERVAL/1000+'s'});
      return false;
    }
    if(input == ""){
      this.msgService.add({severity:'warn', summary:'输入不合法', detail:'评论内容不可为空'});
      return false;
    }
    return true;
  }

  // 在前端添加评论
  private AddCommentAtFront(id:number, type:string, fatherId:number, commentId:number, userId:number, content:string){
    let time = new Date().getTime().toString().substring(0, 10);  // 精确到秒
    let owner = userId==-1?"匿名用户":this.cookieService.get("nickname");
    let date = new Date(parseInt(time+"000"));
    let timeStr = date.getFullYear()+"-"+(date.getMonth()+1)+"-"+date.getDate()+" "+date.toTimeString().substring(0,8);
    let newComment:Comment = {"id":id, "type":type, "fatherId":fatherId, "commentId":commentId, "resCounts":0, "userId":userId, 
      "owner":owner, "time":parseInt(time), "timeStr":timeStr, "content":content, "response":[]};
    if(commentId==-1){  // 一级评论
      this.comments.unshift(newComment);
    }else{  // 二级评论
      for(let index in this.comments){
        let comment = this.comments[index];
        if(comment["id"] == commentId){
          comment["response"].push(newComment);
          comment["resCounts"] += 1;
          break;
        }
      }
    }
  }
}